package com.dhcc.sds.busi.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.excel.write.style.column.SimpleColumnWidthStyleStrategy;
import com.baomidou.mybatisplus.plugins.Page;
import com.dhcc.core.config.properties.SysProperties;
import com.dhcc.core.framework.util.CommonUtil;
import com.dhcc.sds.base.entity.SdsQcfitemDicEntity;
import com.dhcc.sds.base.entity.SdsQcformItemEntity;
import com.dhcc.sds.base.service.ISdsQcfitemDicService;
import com.dhcc.sds.base.service.ISdsQcformItemService;
import com.dhcc.sds.busi.dao.SdsCaseMapper;
import com.dhcc.sds.busi.dto.SdsCaseDto;
import com.dhcc.sds.busi.service.ISdsCaseService;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("sdsCaseService")
public class SdsCaseServiceImpl implements ISdsCaseService {
    @Autowired
    private SysProperties sysPro;
    @Autowired
    private SdsCaseMapper sdsCaseMapper;
    @Autowired
    private ISdsQcfitemDicService sdsQcfitemDicService;
    @Autowired
    private ISdsQcformItemService sdsQcformItemService;

    @Override
    public List<SdsCaseDto> page(Page<SdsCaseDto> page, Map<String, Object> map) {
        return sdsCaseMapper.caseList(page, map);
    }

    @Override
    public List<Map<String, Object>> page2(Page<Map<String, Object>> page, Map<String, Object> map) {
        List<Map<String, Object>> resultList = new ArrayList<>();
        List<Map<String, Object>> caseList = sdsCaseMapper.caseList2(page, map);
        for (Map<String, Object> caseMap : caseList) {
            Long qcincaseId = (Long) caseMap.get("qcincaseId");
            Long entityId = (Long) caseMap.get("entityId");
            HashMap<String, Object> qryMap = new HashMap<>();
            qryMap.put("incaseId",qcincaseId);
            qryMap.put("entityId",entityId);
            List<Map<String, Object>> caseExecResultList = sdsCaseMapper.selectCaseExecResultList(qryMap);
            for (Map<String, Object> resMap : caseExecResultList) {
                caseMap.put(resMap.get("formItemId").toString(), resMap.get("itemResult"));
                String description = (String) resMap.get("description");
                if (CommonUtil.isEmpty(description)) {
                    continue;
                }
                if (description.contains("字典") && description.contains("多选")) {
                    HashMap<String, Object> qryItemDicMap = new HashMap<>();
                    qryItemDicMap.put("formItemId", resMap.get("formItemId"));
                    List<SdsQcfitemDicEntity> qcfitemDicEntityList = sdsQcfitemDicService.list(qryItemDicMap);
                    String itemResult = (String) resMap.get("itemResult");
                    if (CommonUtil.isEmpty(itemResult)) {
                        continue;
                    }
                    String[] split = itemResult.split(",");
                    String tmpResult = "";
                    for (String code : split) {
                        for (SdsQcfitemDicEntity sdsQcfitemDicEntity : qcfitemDicEntityList) {
                            if (sdsQcfitemDicEntity.getCode().equals(code)) {
                                tmpResult += sdsQcfitemDicEntity.getDesc() + ";";
                                break;
                            }
                        }
                    }
                    caseMap.put(resMap.get("formItemId").toString(), tmpResult);
                } else if (description.contains("字典")) {
                    HashMap<String, Object> qryItemDicMap = new HashMap<>();
                    qryItemDicMap.put("formItemId", resMap.get("formItemId"));
                    List<SdsQcfitemDicEntity> qcfitemDicEntityList = sdsQcfitemDicService.list(qryItemDicMap);
                    for (SdsQcfitemDicEntity sdsQcfitemDicEntity : qcfitemDicEntityList) {
                        if (sdsQcfitemDicEntity.getCode().equals(resMap.get("itemResult"))) {
                            caseMap.put(resMap.get("formItemId").toString(), sdsQcfitemDicEntity.getDesc());
                            break;
                        }
                    }
                }
            }
            resultList.add(caseMap);
        }
        return resultList;
    }

    @Override
    public List<SdsCaseDto> caseList(Map<String, Object> map) {
        return sdsCaseMapper.caseList(map);
    }

    @Override
    @Transactional
    public String createExcel(Map<String, Object> map) {
        List<SdsCaseDto> excelExport = sdsCaseMapper.caseList(map);
        String filePath = sysPro.getSysHome()+"file_download/sds/case/";
        File file = new File(filePath);
        if (!file.exists()) file.mkdirs();
        String fileName = "单病种病例导出数据_" + com.dhcc.core.framework.util.DateUtil.getDays() + ".xlsx";
        File outFile = new File(filePath + fileName);
        try {
            EasyExcel.write(new FileOutputStream(outFile), SdsCaseDto.class).sheet("入组病例列表").doWrite(excelExport);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
//        ExcelExportUtil.exportToFile(filePath + fileName, excelExport);
        return fileName;
    }

    @Override
    @Transactional
    public String createExcel2(Map<String, Object> map) {
        if (CommonUtil.isEmpty(map.get("entityType"))) {
            return "请选择病种";
        }
        HashMap<String, Object> qryColumnMap = new HashMap<>();
        // 获取表头
        qryColumnMap.put("entityId", map.get("entityType"));
        List<SdsQcformItemEntity> caseColumn = getCaseColumn(qryColumnMap);
        List<List<String>> columnHeaders = new ArrayList<>();
        List<String> columnNameList = new ArrayList<>();
        columnNameList.add("caseName");
        columnNameList.add("isReport");
        List<String> head1 = new ArrayList<>();
        head1.add("患者姓名");
        List<String> head2 = new ArrayList<>();
        head2.add("是否上报");
        columnHeaders.add(head1);
        columnHeaders.add(head2);
        for (SdsQcformItemEntity sdsQcformItemEntity : caseColumn) {
            List<String> head = new ArrayList<>();
            head.add(sdsQcformItemEntity.getBtDesc());
            columnNameList.add(sdsQcformItemEntity.getId().toString());
            columnHeaders.add(head);
        }
        // 获取数据
        List<List<Object>> columnData = dataList(map, columnNameList);
        String filePath = sysPro.getSysHome()+"file_download/sds/case/";
        File file = new File(filePath);
        if (!file.exists()) file.mkdirs();
        String fileName = "单病种病例导出数据_" + com.dhcc.core.framework.util.DateUtil.getDays() + ".xlsx";

        EasyExcel.write(filePath + fileName)
                .head(columnHeaders)
                .sheet("入组病例列表")
                .registerWriteHandler(writeCenterStyle())
                .registerWriteHandler(new SimpleColumnWidthStyleStrategy(25))
                .doWrite(columnData);
        return fileName;
    }

    private List<List<Object>> dataList(Map<String, Object> map, List<String> columnNameList) {
        List<List<Object>> resultList = new ArrayList<>();
        
        List<Map<String, Object>> columnDataList = new ArrayList<>();
        List<Map<String, Object>> caseList = sdsCaseMapper.caseList2(map);
        for (Map<String, Object> caseMap : caseList) {
            Map<String, Object> columnData = new HashMap<>();
            columnData.put("caseName", caseMap.get("caseName"));
            columnData.put("isReport", caseMap.get("isReport"));
            Long qcincaseId = (Long) caseMap.get("qcincaseId");
            Long entityId = (Long) caseMap.get("entityId");
            HashMap<String, Object> qryMap = new HashMap<>();
            qryMap.put("incaseId",qcincaseId);
            qryMap.put("entityId",entityId);
            List<Map<String, Object>> caseExecResultList = sdsCaseMapper.selectCaseExecResultList(qryMap);
            for (Map<String, Object> resMap : caseExecResultList) {
                columnData.put(resMap.get("formItemId").toString(), resMap.get("itemResult"));
                String description = (String) resMap.get("description");
                if (CommonUtil.isEmpty(description)) {
                    continue;
                }
                if (description.contains("字典") && description.contains("多选")) {
                    HashMap<String, Object> qryItemDicMap = new HashMap<>();
                    qryItemDicMap.put("formItemId", resMap.get("formItemId"));
                    List<SdsQcfitemDicEntity> qcfitemDicEntityList = sdsQcfitemDicService.list(qryItemDicMap);
                    String itemResult = (String) resMap.get("itemResult");
                    if (CommonUtil.isEmpty(itemResult)) {
                        continue;
                    }
                    String[] split = itemResult.split(",");
                    String tmpResult = "";
                    for (String code : split) {
                        for (SdsQcfitemDicEntity sdsQcfitemDicEntity : qcfitemDicEntityList) {
                            if (sdsQcfitemDicEntity.getCode().equals(code)) {
                                tmpResult += sdsQcfitemDicEntity.getDesc() + ";";
                                break;
                            }
                        }
                    }
                    columnData.put(resMap.get("formItemId").toString(), tmpResult);
                } else if (description.contains("字典")) {
                    HashMap<String, Object> qryItemDicMap = new HashMap<>();
                    qryItemDicMap.put("formItemId", resMap.get("formItemId"));
                    List<SdsQcfitemDicEntity> qcfitemDicEntityList = sdsQcfitemDicService.list(qryItemDicMap);
                    for (SdsQcfitemDicEntity sdsQcfitemDicEntity : qcfitemDicEntityList) {
                        if (sdsQcfitemDicEntity.getCode().equals(resMap.get("itemResult"))) {
                            columnData.put(resMap.get("formItemId").toString(), sdsQcfitemDicEntity.getDesc());
                            break;
                        }
                    }
                }
            }
            columnDataList.add(columnData);
        }

        for (Map<String, Object> columnData : columnDataList) {
            List<Object> data = new ArrayList<>();
            for (String column : columnNameList) {
                data.add(columnData.get(column));
            }
            resultList.add(data);
        }
        return resultList;
    }

    public HorizontalCellStyleStrategy writeCenterStyle(){
        // 内容的策略
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        //设置 自动换行
//        contentWriteCellStyle.setWrapped(true);
        //设置 垂直居中
        contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        //设置 水平居中
        contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        //设置边框样式
        contentWriteCellStyle.setBorderLeft(BorderStyle.THIN);//细实线
        contentWriteCellStyle.setBorderTop(BorderStyle.THIN);
        contentWriteCellStyle.setBorderRight(BorderStyle.THIN);
        contentWriteCellStyle.setBorderBottom(BorderStyle.THIN);

        WriteFont bodyWriteFont = new WriteFont();
        bodyWriteFont.setFontHeightInPoints((short)11);				// 设置字体大小为20
        //headWriteFont.setItalic(BooleanEnum.TRUE.getBooleanValue());// 设置字体斜体
        contentWriteCellStyle.setWriteFont(bodyWriteFont);
        //contentWriteCellStyle
        // 头部
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        // 设置字体居中
        headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        WriteFont headWriteFont = new WriteFont();
        headWriteFont.setFontHeightInPoints((short)11);				// 设置字体大小为20
        //headWriteFont.setItalic(BooleanEnum.TRUE.getBooleanValue());// 设置字体斜体
        headWriteCellStyle.setWriteFont(headWriteFont);

        return new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
    }


    @Override
    public List<SdsQcformItemEntity> getCaseColumn(Map<String, Object> map) {
        return sdsQcformItemService.list(map);
    }
}
